package com.jh.paymentchannel.helipay.service;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.jh.paymentchannel.helipay.util.HeliPayBase;
import com.jh.paymentchannel.helipay.vo.BalanceQueryVo;
import com.jh.paymentchannel.helipay.vo.CreditCardPaymentVo;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.jifu.DateTime;

import cn.jh.common.utils.CommonConstants;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class CreditCardPaymentService {
	@Autowired
	private Util util;
	@Autowired
	QuickPayApi qpa;
	private static final Logger log = LoggerFactory.getLogger(CreditCardPaymentService.class);
	private String merchant_no = "C1800001614";
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/paymentchannel/pay/creditcardpayment")
	public @ResponseBody Object CreditCardPayment(
			@RequestParam(value = "channe_tag") String channeltag,
			@RequestParam(value = "order_desc") String orderdesc,
			@RequestParam(value = "brand_id", required=false) String brand_id,
			@RequestParam(value = "cardNo", required=false) String cardNo,//到账卡
			@RequestParam(value = "openid", required=false) String openid,
			@RequestParam(value = "phone") String phone,
			@RequestParam(value = "orderCode") String orderCode,
			@RequestParam(value="userid") String userid,
			@RequestParam(value="amount", required=false) String amount) {
		Map<String,Object> map = new HashMap<String,Object>();
		RestTemplate restTemplate=new RestTemplate();
		System.out.println(util);
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/add";
		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("type", "7");
		requestEntity.add("orderCode", orderCode);
		requestEntity.add("phone", phone);
		requestEntity.add("amount", amount);
		requestEntity.add("openid", openid);
		requestEntity.add("channel_tag", "CREDICTPAY");
		requestEntity.add("desc", orderdesc);
		requestEntity.add("bank_card", cardNo);
		requestEntity.add("brand_id", brand_id);
		System.out.println(requestEntity);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/transactionclear/payment/add--RESULT================"+result);
		JSONObject jsonObject =  JSONObject.fromObject(result);
		
		if(!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))){
			 map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			 map.put(CommonConstants.RESP_MESSAGE, "亲.生成订单失败,请联系管理员");
			 return map;
		}
		JSONObject resultObj  =  jsonObject.getJSONObject("result");
		String  order  = resultObj.getString("ordercode");
		String realAmount = resultObj.getString("realAmount");
		if(Float.valueOf(realAmount)<Float.valueOf("1.00"))
			realAmount = "1.00";
		uri = util.getServiceUrl("paymentchannel", "error url request!");
		String road = uri.toString() + "/v1.0/paymentchannel/hlregister/findbycard";
		requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("bankCard",cardNo);
		restTemplate=new RestTemplate();
		String resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
		log.info("接口/v1.0/paymentchannel/hlregister/findbycard--RESULT================"+resultObjx);
		jsonObject =  JSONObject.fromObject(resultObjx);
		JSONObject jsonobj = jsonObject.getJSONObject("result");
		String rt10_bindId = jsonobj.getString("bindId");
		String exemption = jsonobj.getString("exemption");
		
		/*uri = util.getServiceUrl("paymentchannel", "error url request!");
		road = uri.toString() + "/v1.0/paymentchannel/topup/createOrder";
		requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("P1_bizType","AccountQuery");
		requestEntity.add("P2_customerNumber",HeliPayBase.MERCHANT_NO);
		requestEntity.add("P3_userId",userid);
		requestEntity.add("P4_timestamp",time);
		restTemplate=new RestTemplate();
		 resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
		log.info("接口/v1.0/paymentchannel/topup/createOrder--RESULT================"+resultObjx);*/
		String time = DateTime.getNow("yyyyMMddHHmmss");
		BalanceQueryVo orderVo = new BalanceQueryVo();
		orderVo.setP1_bizType("AccountQuery");
		orderVo.setP2_customerNumber(HeliPayBase.MERCHANT_NO);
		orderVo.setP3_userId(userid);
		orderVo.setP4_timestamp(time);
		Object rltObj = qpa.createOrder("AccountQuery", HeliPayBase.MERCHANT_NO, userid, time, orderVo);
		jsonObject =  JSONObject.fromObject(rltObj);
		log.info("============="+jsonObject+"=============");
		String message  = jsonObject.getString("message");
		if("交易成功".equals(message)) {
			 jsonobj = jsonObject.getJSONObject("json");
			 if("0000".equals(jsonobj.getString("rt2_retCode"))) {
				 //amount = jsonobj.getString("rt9_accountBalance");
			 }else {
				 String rt8_accountStatus = jsonobj.getString("rt8_accountStatus");
				 if(!"1".equals(rt8_accountStatus)) {
					 map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					 map.put(CommonConstants.RESP_MESSAGE, "此账户处于非正常状态："+rt8_accountStatus);
					 return map;
				 }
			 }
		}
		
		 /*uri = util.getServiceUrl("paymentchannel", "error url request!");
		 url = uri.toString() + "/v1.0/paymentchannel/topup/creditPay";
		 requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("P1_bizType", "CreditCardRepayment");
		requestEntity.add("P2_customerNumber", merchant_no);
		requestEntity.add("P3_userId", userid);
		requestEntity.add("P4_bindId", rt10_bindId);
		requestEntity.add("P5_orderId", order);
		requestEntity.add("P6_timestamp", time);
		requestEntity.add("P7_currency", "CNY");
		requestEntity.add("P8_orderAmount", amount);
		requestEntity.add("P9_feeType", "PAYER");//扣款方式，从余额里面扣
		requestEntity.add("P10_summary", "");
		 result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/paymentchannel/topup/creditPay--RESULT================"+result);*/
		CreditCardPaymentVo ccpv = new CreditCardPaymentVo();
		ccpv.setP1_bizType("CreditCardRepayment");
		ccpv.setP2_customerNumber(merchant_no);
		ccpv.setP3_userId(userid);
		ccpv.setP4_bindId(rt10_bindId);
		ccpv.setP5_orderId(order);
		ccpv.setP6_timestamp(time);
		ccpv.setP7_currency("CNY");
		ccpv.setP8_orderAmount(amount);
		ccpv.setP9_feeType("PAYER");
		ccpv.setP10_summary("");
		Object result2 = qpa.confirmPay("CreditCardRepayment", merchant_no, userid, rt10_bindId, order, time, "CNY", amount, "PAYER", "", ccpv);
		 jsonObject =  JSONObject.fromObject(result2);
		 log.info("============="+jsonObject+"=============");
		 log.info("jsonObject"+jsonObject);
		 message  = jsonObject.getString("message");
		if("交易成功".equals(message)) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "还款成功");
			map.put(CommonConstants.RESULT, amount);
			uri = util.getServiceUrl("paymentchannel", "error url request!");
			url = uri.toString() + "/v1.0/paymentchannel/automaticrepaymenttask/update";
			requestEntity  = new LinkedMultiValueMap<String, String>();
			requestEntity.add("orderCode", order);
			requestEntity.add("status", "1");
			result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("接口/v1.0/paymentchannel/automaticrepaymenttask/update--RESULT================"+result);
			
			 uri = util.getServiceUrl("transactionclear", "error url request!");
			 url = uri.toString() + "/v1.0/transactionclear/payment/update";
			 requestEntity  = new LinkedMultiValueMap<String, String>();
			 requestEntity.add("status", "1");
			 requestEntity.add("order_code",   order);
			 result = restTemplate.postForObject(url, requestEntity, String.class);
			 log.info("接口/v1.0/transactionclear/payment/update--RESULT================"+result);
			if("1".equals(exemption)) {
				uri = util.getServiceUrl("paymentchannel", "error url request!");
				url = uri.toString() + "/v1.0/paymentchannel/hlregister/update";
				requestEntity  = new LinkedMultiValueMap<String, String>();
				requestEntity.add("bindId", rt10_bindId);
				requestEntity.add("exemption", "2");
				result = restTemplate.postForObject(url, requestEntity, String.class);
				log.info("接口/v1.0/paymentchannel/hlregister/update--RESULT================"+result);
			}
		}else {
			uri = util.getServiceUrl("paymentchannel", "error url request!");
			url = uri.toString() + "/v1.0/paymentchannel/automaticrepaymenttask/update";
			requestEntity  = new LinkedMultiValueMap<String, String>();
			requestEntity.add("orderCode", order);
			requestEntity.add("status", "2");
			result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("接口/v1.0/paymentchannel/automaticrepaymenttask/update--RESULT================"+result);
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, message);
		}
		return map;
	}
}
